<template>
  <el-form-item label="参数设置">
    <el-tag>{{ paramsSettedTag }}</el-tag>
    <text-edit-button text="编辑参数" @click="showParamsSetting = true" />
  </el-form-item>
  <el-form-item label="执行前钩子" v-if="localData.params">
    <el-select v-model="localData.params.hookBefore" filterable clearable>
      <el-option v-for="opt in getPageFuncs()" :key="opt.funcName" :label="opt.funcLabel" :value="opt.funcName" />
    </el-select>
  </el-form-item>
  <el-form-item label="调用">
    <comp-call-config v-model="localData.components" :fields="fields" :options="options" />
  </el-form-item>
  <params-setting v-if="showParamsSetting" v-model="showParamsSetting" :data="localData.params" :fields="fields" :options="options" @submit="handleParamsSubmit" />
</template>

<script>
import paramsSetting from './paramsSetting.vue';

export default {
  name: 'CustomEventCall',
  components: { paramsSetting },
  props: {
    modelValue: {
      type: Object,
      default: () => {}
    },
    options: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      localData: {},
      showParamsSetting: false,
      paramsSettedTag: ''
    };
  },
  computed: {
    fields() {
      return this.getCallableCompList(this.options);
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.localData = newVal;
      },
      immediate: true,
      deep: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal);
      },
      deep: true
    }
  },
  mounted() {
    this.getParamsSettedTag();
  },
  methods: {
    handleParamsSubmit(data) {
      for (let key in data) {
        this.localData.params[key] = data[key];
      }
      this.getParamsSettedTag();
    },
    getParamsSettedTag() {
      this.paramsSettedTag = this.isParamsSetted();
    },
    isParamsSetted() {
      if (this.localData.params && Object.keys(this.localData.params).length) {
        const { contantParams, compParams, withFormData } = this.localData.params;
        const strArr = [];
        if (contantParams && contantParams.length) {
          strArr.push('常量参数');
        }
        if (compParams && compParams.length) {
          strArr.push('组件参数');
        }
        if (withFormData) {
          strArr.push('表单数据');
        }

        return strArr.length ? strArr.join(',') : '未设置';
      } else {
        return '未设置';
      }
    },
    getPageFuncs() {
      return this.options.funcs ?? [];
    }
  }
};
</script>